package cn.wizzer.app.web.commons.filter;

import cn.wizzer.app.user.modules.models.enums.EquipmentEnum;
import cn.wizzer.app.web.commons.utils.TokenUtil;
import cn.wizzer.framework.util.Result;
import cn.wizzer.framework.base.model.enums.BizExceptionEnum;
import org.apache.commons.lang3.EnumUtils;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.View;
import org.nutz.mvc.view.UTF8JsonView;


/**
 * JWT Token拦截器
 * Created by wizzer on 2016/8/11.
 */
public class ApiTokenFilter implements ActionFilter {
    private static final Log log = Logs.get();

    protected String origin;
    protected String methods;
    protected String headers;
    protected String credentials;


    public ApiTokenFilter() {
        this("*", "GET, POST, PUT, DELETE, OPTIONS, PATCH", "appid,token,equipment,Origin, Content-Type, Accept, X-Requested-With", "true");
    }

    public ApiTokenFilter(String origin, String methods, String headers, String credentials) {
        this.origin = origin;
        this.methods = methods;
        this.headers = headers;
        this.credentials = credentials;
    }

    @Override
    public View match(ActionContext context) {
        try {
            String appid = Strings.sNull(context.getRequest().getParameter("appid"));
            if (Strings.isBlank(appid)) {
                appid = Strings.sNull(context.getRequest().getHeader("appid"));
            }

            String token = Strings.sNull(context.getRequest().getParameter("token"));
            if (Strings.isBlank(token)) {
                token = Strings.sNull(context.getRequest().getHeader("token"));
            }
            // 非临时的
            if (!appid.contains("TEMPID")) {
                if (!context.getIoc().get(TokenUtil.class).verifyToken(appid, token)) {
                    return new UTF8JsonView(JsonFormat.compact()).setData(Result.error(-2, BizExceptionEnum.LOGIN_EXCEPTION));
                }
            }


            return null;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return new UTF8JsonView(JsonFormat.compact()).setData(Result.error());
        }
    }
}
